<template>
	<div class="game-container report-container">
		<div class="view-container dealer-container">
			<div class="params">
				<el-form ref="form" :inline="true" :model="queryData">
					<el-form-item label="会员账号:" prop="userName">
						<el-input
							v-model="queryData.userName"
							placeholder="请输入"
							clearable
							style="width: 180px"
							maxlength="11"
						></el-input>
					</el-form-item>
					<el-form-item label="申请金额:">
						<el-input
							v-model="queryData.depositVenueAmountMin"
							:controls="false"
							placeholder="最小数值"
							maxlength="10"
							style="width: 100px"
							name="totalDepositAmountMin"
							@change="vipSerialNumFn"
						></el-input>
						-
						<el-input
							v-model="queryData.depositVenueAmountMax"
							:controls="false"
							maxlength="10"
							placeholder="最大数值"
							style="width: 100px"
							name="totalDepositAmountMax"
							@change="vipSerialNumFn"
						></el-input>
					</el-form-item>
					<el-form-item label="申请场馆:">
						<el-select
							v-model="queryData.gameCode"
							clearable
							placeholder="默认选择全部"
							:popper-append-to-body="false"
						>
							<el-option
								:label="'全部'"
								:value="undefined"
							></el-option>
							<el-option
								v-for="item in loginDeviceType"
								:key="item.gameCode"
								:label="item.gameName"
								:value="item.gameCode"
							></el-option>
						</el-select>
					</el-form-item>

					<el-form-item label="是否过有效期:">
						<el-select
							v-model="queryData.taskEnd"
							clearable
							placeholder="默认选择全部"
							:popper-append-to-body="false"
						>
							<el-option
								:label="'全部'"
								:value="undefined"
							></el-option>
							<el-option label="是" :value="1"></el-option>
							<el-option label="否" :value="0"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="申请时间:" class="time-options">
						<el-date-picker
							v-model="searchTime"
							:picker-options="pickerOptions1"
							format="yyyy-MM-dd HH:mm:ss"
							type="datetimerange"
							range-separator="-"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							align="right"
							:clearable="true"
							:default-time="defaultTime"
							style="width: 375px"
							class="time-options-value"
						></el-date-picker>
					</el-form-item>
					<el-form-item class="">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="flag"
							@click="search"
						>
							{{ queryText }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							:disabled="resetFlag"
							@click="reset"
						>
							重置
						</el-button>
						<el-button
							v-if="hasPermission('347')"
							icon="el-icon-download"
							type="warning"
							:disabled="loading"
							@click="exportExcel"
						>
							导出
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<div class="content">
				<CommonTable
					ref="hasTotalTable"
					:loading="loading"
					:datas="tableOptions.datas"
					:fieldList="tableOptions.fieldList"
					:operation="tableOptions.operation"
					:pageObj="pageObj"
					:summary="tableOptions.summary"
					:getSummariesObj="tableOptions.getSummariesObj"
					:loadData="loadData"
				></CommonTable>
				<!-- 分页 -->
				<!-- <el-pagination
					:current-page.sync="pageNum"
					background
					class="fenye"
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="[10, 20, 50]"
					:total="total"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination> -->
			</div>
		</div>
	</div>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import CommonTable from '@/components/CommonTable'
export default {
	name: routerNames.clientProfitAndLoss,
	components: {
		CommonTable
	},
	mixins: [list],
	data() {
		return {
			tableOptions: {
				datas: [],
				fieldList: [
					{
						label: '会员账号',
						prop: 'userName',
						filter: (val) => val || '-',
						show: true
					},
					{
						label: '角色',
						prop: 'recordType',
						filter: (val) => {
							if (val) {
								return {
									1: '邀请人',
									2: '被邀请人'
								}[val]
							} else {
								return '-'
							}
						},
						show: true
					},
					{
						label: '注册时间',
						prop: 'registerAt',
						filter: (val) => val || '-',
						orderColumn: true,
						show: true
					},
					{
						label: '是否过有效期',
						prop: 'taskEnd',
						filter: (val) => val || '-',
						show: true
					},
					{
						label: '申请时间',
						prop: 'applyAt',
						orderColumn: true,
						filter: (val) => val || '-',
						show: true
					},
					{
						label: '申请场馆',
						prop: 'gameCode',
						// orderColumn: true,
						filter: (val) => this.filterVenue(val),
						show: true
					},
					{
						label: '申请金额',
						prop: 'depositVenueAmount',
						orderColumn: true,
						filter: (val) => this.formatMoney(val),
						show: true
					},
					{
						label: '奖励金额',
						prop: 'rewardAmount',
						orderColumn: true,
						filter: (val) => this.formatMoney(val),
						show: true
					},
					{
						label: '流水倍数',
						prop: 'validMultiple',
						filter: (val) => val || '-',
						show: true
					}
				],
				summary: {
					show: true,
					showTotal: false,
					datas: {},
					// 小计
					columns: [
						{
							depositVenueAmount: '申请金额',
							key: 'depositVenueAmount',
							filter: (val) => this.formatMoney(val)
						},
						{
							rewardAmount: '奖励金额',
							key: 'rewardAmount',
							filter: (val) => this.formatMoney(val)
						}
					],
					// 总计
					totalColumns: [
						{
							depositVenueAmount: '申请金额',
							key: 'totalDepositVenueAmount',
							filter: (val) => this.formatMoney(val)
						},
						{
							rewardAmount: '奖励金额',
							key: 'totalRewardAmount',
							filter: (val) => this.formatMoney(val)
						}
					]
				}
			},
			queryData: {},
			searchTime: [],
			day31: 31 * 24 * 3600 * 1000,
			flag: false,
			resetFlag: false,
			queryText: '查询',
			tableData: [],
			dialogList: [],
			pageR: 1,
			sizeR: 10,
			dialogTotal: 0,
			deviceTypeCode: '',
			summary: null,
			title: '',
			visible: false,
			loadingDialog: false,
			loadChangGuanLIst: [],
			//
			clientProfitAndLoss: {
				客户端: true,
				投注人数: true,
				注单量: true,
				投注金额: true,
				有效投注: true,
				投注盈亏: true
			},
			myName: '',
			newList: [],
			timecount: null,
			pageObj: {
				show: true,
				pageTotal: 0
			}
		}
	},
	computed: {
		loginDeviceType() {
			return [...this.loadChangGuanLIst]
		}
	},
	watch: {
		'queryData.depositVenueAmountMin': function(val) {
			if (val) {
				val = val.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
				val = val.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
				val = val
					.replace('.', '$#$')
					.replace(/\./g, '')
					.replace('$#$', '.')
				val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
				if (
					val.indexOf('.') < 0 &&
					val !== '' &&
					val.indexOf('0') === 0 &&
					val.length > 1
				) {
					// 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
					val = val.replace('0', '')
				}
				this.queryData.depositVenueAmountMin = val
			}
		},
		'queryData.depositVenueAmountMax': function(val) {
			if (val) {
				val = val.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
				val = val.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
				val = val
					.replace('.', '$#$')
					.replace(/\./g, '')
					.replace('$#$', '.')
				val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
				if (
					val.indexOf('.') < 0 &&
					val !== '' &&
					val.indexOf('0') === 0 &&
					val.length > 1
				) {
					// 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
					val = val.replace('0', '')
				}
				this.queryData.depositVenueAmountMax = val
			}
		},
		tableColumnData: {
			handler(val) {
				this.tableOptions.fieldList.forEach((item) => {
					for (const key in val) {
						if (item.label === key) {
							item.show = val[key]
						}
					}
				})
			},
			// immediate: true,
			deep: true
		}
	},
	created() {
		// 获取场馆的下拉列表数据
		this.loadChangGuan()
	},
	mounted() {
		this.initIndexDB('InvitationData', this.clientProfitAndLoss)
	},
	methods: {
		filterVenue(va) {
			if (!va) return '-'
			const venue = []
			this.loginDeviceType?.length > 0 &&
				this.loginDeviceType.map((val) => {
					if (va?.split(',').includes(val.gameCode)) {
						venue.push(val.gameName)
					}
				})
			return venue.length && venue.join(',')
		},
		loadChangGuan() {
			this.$api
				.getMerchantGameGetMerchantGames()
				.then((res) => {
					const { code } = res
					if (res && code && code === 200) {
						if (res.code === 200) {
							this.loadChangGuanLIst = res?.data || []
						}
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		vipSerialNumFn(val) {
			if (val === '') return
			if (
				(+val < +this.queryData.depositVenueAmountMin &&
					this.queryData.depositVenueAmountMin) ||
				(+val > +this.queryData.depositVenueAmountMax &&
					this.queryData.depositVenueAmountMax)
			) {
				// eslint-disable-next-line no-extra-semi
				;[
					this.queryData.depositVenueAmountMin,
					this.queryData.depositVenueAmountMax
				] = [
					this.queryData.depositVenueAmountMax,
					this.queryData.depositVenueAmountMin
				]
			}
		},
		// 列设置
		openSetting() {
			this.getIndexDB(this.clientProfitAndLoss)
			this.dialogShowHide = true
		},
		clickDel() {
			this.dialogColumnData = {}
			this.dialogColumnData = this.clientProfitAndLoss
		},
		loadData(orderParams) {
			if (this.queryData.gameCode === '') {
				delete this.queryData.gameCode
			}
			if (this.queryData.taskEnd === '') {
				delete this.queryData.taskEnd
			}
			if (orderParams) {
				const { orderType, orderKey } = orderParams
				// 1-注册时间 2-申请时间 3-申请场馆 4-申请金额 5-奖励金额
				const obj = {
					registerAt: 1,
					applyAt: 2,
					gameCode: 3,
					depositVenueAmount: 4,
					rewardAmount: 5
				}
				this.queryData.orderKey = obj[orderKey]
				this.queryData.orderType = orderType
			}
			const create = this.searchTime || []
			const [startTime, endTime] = create
			const params = {
				exportFlag: true,
				...this.$refs.hasTotalTable.getParams(),
				queryCondition: {
					...this.queryData,
					applyAtStart: startTime
						? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss') // HH:mm:ss
						: '',
					applyAtEnd: endTime
						? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
						: ''
				}
			}

			// if (endTime - startTime >= this.day31) {
			// 	this.$message.warning('请缩小搜索范围至31天')
			// } else {
			this.loading = true
			Promise.all([this.$api.geInviteDepositPageApi(params)])
				.then(([res]) => {
					if (res.code === 200) {
						this.tableOptions.datas = []
						this.tableData = res?.data?.record || []
						this.pageObj.pageTotal = res?.data?.totalRecord || 0
						this.tableOptions.datas = this.tableData || []
						this.tableOptions.summary.datas = res?.data.summary || 1
						this.tableOptions.summary.show = true
						this.tableOptions.summary.showTotal = true
						this.loading = false
					}
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
			// }
		},
		search() {
			this.$refs.hasTotalTable.pageNum = 1
			this.loadData()
		},
		reset() {
			// const S = dayjs()
			// 	.startOf('day')
			// 	.valueOf()
			// const E = dayjs()
			// 	.endOf('day')
			// 	.valueOf()
			this.queryData = {}
			this.searchTime = []
			this.$refs.hasTotalTable.pageNum = 1
			this.search()
		},
		exportExcel() {
			const create = this.searchTime || []
			const [startTime, endTime] = create
			const params = {
				exportFlag: true,
				// ...this.getParams(),
				// queryCondition: {
				...this.$refs.hasTotalTable.getParams(this.queryData),
				applyAtStart: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss') //
					: '',
				applyAtEnd: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: ''
				// }
			}

			this.$confirm(
				`<strong>是否导出?</strong></br><span style='font-size:12px;color:#c1c1c1'>数据过大时，请耐心等待</span>`,
				'确认提示',
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
				.then(() => {
					this.loading = true

					this.$api
						.getAccessAmountDaylitexportExcelApi(params)
						.then((res) => {
							this.loading = false
							const { data, status } = res
							if (res && status === 200) {
								const { type } = data
								if (type.includes('application/json')) {
									const reader = new FileReader()
									reader.onload = (evt) => {
										if (evt.target.readyState === 2) {
											const {
												target: { result }
											} = evt
											const ret = JSON.parse(result)
											if (ret.code !== 200) {
												this.$message({
													type: 'error',
													message: ret.msg,
													duration: 1500
												})
											}
										}
									}
									reader.readAsText(data)
								} else {
									const result = res.data
									const disposition =
										res.headers['content-disposition']
									const fileNames =
										disposition && disposition.split("''")
									let fileName = fileNames[1]
									fileName = decodeURIComponent(fileName)
									const blob = new Blob([result], {
										type: 'application/octet-stream'
									})
									if (
										'download' in
										document.createElement('a')
									) {
										const downloadLink = document.createElement(
											'a'
										)
										downloadLink.download = fileName || ''
										downloadLink.style.display = 'none'
										downloadLink.href = URL.createObjectURL(
											blob
										)
										document.body.appendChild(downloadLink)
										downloadLink.click()
										URL.revokeObjectURL(downloadLink.href)
										document.body.removeChild(downloadLink)
									} else {
										window.navigator.msSaveBlob(
											blob,
											fileName
										)
									}
									this.$message({
										type: 'success',
										message: '导出成功',
										duration: 1500
									})
								}
							}
						})
						.catch(() => {
							this.loading = false
							// this.$message({
							// 	type: 'error',
							// 	message: '导出失败',
							// 	duration: 1500
							// })
						})
				})
				.catch(() => {
					this.loading = false
				})
		}
	}
}
</script>

<style lang="scss" scoped>
.chechox {
	display: flex;
	flex-direction: column;
	height: 400px;
	overflow-y: auto;
}
::v-deep .el-dialog__header {
	color: #5c5c5c;
	font-weight: 700;
}
.count_row {
	height: 80px;
	color: #5c5c5c;
	p {
		height: 40px;
		line-height: 40px;
		font-weight: 700;

		span {
			display: inline-block;
			width: 20px;
			height: 20px;
		}
	}
}
.fenye {
	text-align: center;
}
.setting-div {
	display: inline-block;
	min-width: 90px;
}
</style>
